<?php
/**
 * tmaic.com 
 * ============================================================================
 * * 版权所有 2020-2030 tmaic，并保留所有权利。
 * 网站地址: http://www.tmaic.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: pangxianfei
 * $email:421339244@qq.com
 * $phone:18929142226
 * $date 2020-11-13
*/
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Requests\NavigationRequest;

use App\Models\Navigation;
use App\Http\Controllers\AdminController;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\DB;

class NavigationController extends AdminController
{
    /**
     * 列表
     * @return \Illuminate\Contracts\View\View
     */
    public function index()
    {
        $Navigation = [];
	   
        return View::make('admin.navigation.index',compact('Navigation'));
    }

    /**
     * 数据接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function data(Request $request)
    {
        $model = Navigation::query();

        
        $res = $model->orderBy('sort','asc')->get();

        $data = [
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $res->count(),
            'data'  => $res,
        ];
        return Response::json($data);
    }

    /**
     * 添加
     * @return \Illuminate\Contracts\View\View
     */
    public function create()
    {
       
        $Navigation = new Navigation;
        $Navigations = Navigation::with('allChilds')->where('parent_id', 0)->get();
	 
        return View::make('admin.navigation.create',compact('Navigations'));
    }

    /**
     * 添加
     * @param NavigationRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(NavigationRequest $request)
    {
        $data = $request->all();
		$data['spm'] = $data['spm']??$this->gen_invite_code();
        try{
            $Navigation = Navigation::create($data);
            return Redirect::to(URL::route('admin.nav'))->with(['success'=>'添加成功']);
        }catch (\Exception $exception){
            return Redirect::back()->withErrors('添加失败');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * 更新
     * @param $id
     * @return \Illuminate\Contracts\View\View
     */
    public function edit($id)
    {
 
        $Navigation = Navigation::findOrFail($id);
        $Navigations = Navigation::with('allChilds')->where('parent_id', 0)->get();
        return View::make('admin.navigation.edit',compact('Navigation','Navigations'));
    }


	public function gen_invite_code() {
		$chars = "0123456789";
		$res = "";
		while (true) {
			for ($i = 0; $i < 6; $i++) {
				$res .= $chars[mt_rand(0, strlen($chars)-1)];
				if($i == 2) $res .=".";
			}
			$nav = Navigation::where('spm', $res)->first();
			if (!$nav) {
				break;
			}
		}
		return $res;
	}


    /**
     * 更新
     * @param NavigationRequest $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(NavigationRequest $request)
    { 
	    $id = (int)$request->id;
        $Navigation= Navigation::findOrFail($id);
        $data = $request->all();
		
		
		if(empty($data['spm'])){
			
			$data['spm'] = $this->gen_invite_code();
		}
		
	    $Navigation->update($data);
        try{
           $Navigation->update($data);
           return Redirect::to(URL::route('admin.nav'))->with(['success'=>'更新成功']);
        }catch (\Exception $exception){
            return Redirect::back()->withErrors('更新失败');
        }
    }

    public function destroy(Request $request)
    {
        $ids = $request->get('ids');
        if (!is_array($ids) || empty($ids)){
            return Response::json(['code'=>1,'msg'=>'请选择删除项']);
        }
        DB::beginTransaction();
        try{
            Navigation::whereIn('id',$ids)->delete();
            DB::commit();
            return Response::json(['code'=>0,'msg'=>'删除成功']);
        }catch (\Exception $exception){
            DB::rollback();
            return Response::json(['code'=>1,'msg'=>'删除失败','data'=>$exception->getMessage()]);
        }
    }












}
